package com.mall.autoconfig.template;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.mall.autoconfig.properties.OssProperties;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.InputStream;
import java.util.UUID;

public class OssTemplate {

    @Autowired
    private OssProperties ossProperties;


    public String upload(String fileNmae,InputStream is){

        //截取文件名的扩展名
        String[] split = fileNmae.split("\\.");

        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        //通过时间+uuid生成新的文件名
        String objectName = new DateTime().toString("yyyy-MM-dd")+"/"+ UUID.randomUUID()+"."+split[split.length-1];


        // 创建OSSClient实例。
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(), ossProperties.getAccessKey(), ossProperties.getSecret());

        try {
            // 创建PutObject请求。
            ossClient.putObject(ossProperties.getBucketName(), objectName, is);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        //返回网络地址
        String url = ossProperties.getUrl()+objectName;
        return url;

    }








}
